import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/gestures.dart';
import 'package:get/get.dart';
import '../../controller/auth_controller.dart';
import '../../controller/setting_controller.dart';
import '../../controller/home_controller.dart';
import '../../controller/admob_controller.dart';
import '../../widgets/invite_rewards_bottom_sheet.dart';
import '../../widgets/web_view_page.dart';
import '../../widgets/wallet_bottom_sheet.dart';
import '../../widgets/invite_code_dialog.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';

class UserDrawer extends StatelessWidget {
  final AuthController authController = Get.find();
  final SettingController helpController = Get.find();
  final HomeController homeController = Get.put(HomeController());

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topRight,
            end: Alignment.bottomLeft,
            colors: [
              Color(0x30E6B450), // 淡金色 (18% 透明度)
              Color(0xFF2A2A2A), // 主背景色 - 深灰色
            ],
            stops: [0.33, 1.0], // 金色占三分之一
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 用户信息区域
              _buildUserHeader(),

              // 菜单项列表
              Expanded(
                child: ListView(
                  padding: EdgeInsets.zero,
                  children: [
                    _buildMenuItem(
                      icon: Icons.share,
                      iconColor: const Color(0xFFE6B450),
                      title: 'Share & Earn Rewards',
                      onTap: () {
                        Get.back();
                        showModalBottomSheet(
                          context: context,
                          isScrollControlled: true,
                          backgroundColor: Colors.transparent,
                          builder: (context) => InviteRewardsBottomSheet(),
                        );
                      },
                    ),
                    _buildMenuItem(
                      icon: Icons.campaign,
                      iconColor: const Color(0xFFE6B450),
                      title: 'Announcements',
                      onTap: () {
                        Get.back();
                        _showAnnouncementsDialog();
                      },
                    ),
                    _buildMenuItem(
                      icon: Icons.account_balance_wallet,
                      iconColor: const Color(0xFFE6B450),
                      title: 'My Wallet',
                      onTap: () {
                        // 先关闭抽屉，然后使用延迟确保抽屉动画完成后再显示钱包
                        Get.back();
                        Future.delayed(Duration(milliseconds: 300), () {
                          WalletBottomSheet.show();
                        });
                      },
                    ),
                    _buildMenuItem(
                      icon: Icons.help_center,
                      iconColor: const Color(0xFFE6B450),
                      title: 'Help Center',
                      onTap: () {
                        Get.back();
                        // 使用邮件方式联系帮助中心
                        final Uri emailLaunchUri = Uri(
                          scheme: 'mailto',
                          path: 'liuyiqwef@gmail.com',
                          query:
                              'subject=Help Center Support&body=I need assistance with...',
                        );
                        launchUrl(emailLaunchUri);
                      },
                    ),
                    _buildMenuItem(
                      icon: Icons.link,
                      iconColor: const Color(0xFFE6B450),
                      title: 'Bind Invitation Code',
                      onTap: () {
                        Get.back();
                        _showInvitationCodeDialog();
                      },
                    ),
                    _buildMenuItem(
                      icon: Icons.description,
                      iconColor: const Color(0xFFE6B450),
                      title: 'User Agreement',
                      onTap: () {
                        Get.back();
                        Get.to(() => WebViewPage(
                              url: helpController
                                      .userAgreementUrl.value.isNotEmpty
                                  ? helpController.userAgreementUrl.value
                                  : 'https://doc.bit-fury.com/',
                              title: 'User Agreement',
                            ));
                      },
                    ),
                    _buildMenuItem(
                      icon: Icons.privacy_tip,
                      iconColor: const Color(0xFFE6B450),
                      title: 'Privacy Policy',
                      onTap: () {
                        Get.back();
                        Get.to(() => WebViewPage(
                              url: helpController
                                      .privacyPolicyUrl.value.isNotEmpty
                                  ? helpController.privacyPolicyUrl.value
                                  : 'https://doc.bit-fury.com/privacy-policy',
                              title: 'Privacy Policy',
                            ));
                      },
                    ),
                    _buildMenuItem(
                      icon: Icons.lock_reset,
                      iconColor: const Color(0xFFE6B450),
                      title: 'Reset Privacy Consent',
                      onTap: () {
                        Get.back();
                        _showResetConsentDialog(context);
                      },
                    ),
                    _buildMenuItem(
                      icon: Icons.delete_forever,
                      iconColor: const Color(0xFFE6B450),
                      title: 'Delete Account',
                      onTap: () {
                        Get.back();
                        _showDeleteAccountDialog(context);
                      },
                    ),
                    _buildMenuItem(
                      icon: Icons.logout,
                      iconColor: const Color(0xFFE6B450),
                      title: 'Log Out',
                      onTap: () {
                        Get.back();
                        _showLogoutDialog(context);
                      },
                    ),
                  ],
                ),
              ),

              // 版本信息
              _buildVersionInfo(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildUserHeader() {
    return Obx(() {
      return Container(
        padding: const EdgeInsets.fromLTRB(20, 20, 20, 0),
        child: Column(
          children: [
            // 用户头像和基本信息
            Row(
              children: [
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    color: Colors.grey[700],
                    shape: BoxShape.circle,
                    image: const DecorationImage(
                      image: AssetImage("assets/app_logo.png"),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'BitPlanera',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        'ID: ${authController.userId.isNotEmpty ? authController.userId : '0'}',
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),

            const SizedBox(height: 20),

            // BTC余额显示 - 毛玻璃效果 (响应式设计)
            LayoutBuilder(
              builder: (context, constraints) {
                final screenWidth = MediaQuery.of(context).size.width;
                final isSmallScreen = screenWidth < 360;

                return ClipRRect(
                  borderRadius: BorderRadius.circular(isSmallScreen ? 6 : 8),
                  child: BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                    child: Container(
                      padding: EdgeInsets.symmetric(
                          vertical: isSmallScreen ? 10 : 12,
                          horizontal: isSmallScreen ? 12 : 16),
                      decoration: BoxDecoration(
                        color: const Color(0xFF2A2A2A).withOpacity(0.3),
                        borderRadius:
                            BorderRadius.circular(isSmallScreen ? 6 : 8),
                        border: Border.all(
                          color: const Color(0xFFE6B450).withOpacity(0.2),
                          width: 1,
                        ),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "Invite Rewards",
                            style: TextStyle(
                              fontSize: isSmallScreen ? 11 : 11,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          SizedBox(height: 5,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              // Image(
                              //   image: const AssetImage(
                              //       "assets/bit_bitcoin_logo.png"),
                              //   width: isSmallScreen ? 18 : 20,
                              //   height: isSmallScreen ? 18 : 20,
                              // ),
                              // SizedBox(width: isSmallScreen ? 6 : 8),
                              Expanded(
                                child: Obx(() => Text(
                                      homeController.invitBalance,
                                      style: TextStyle(
                                        color: const Color(0xFFE6B450),
                                        fontSize: isSmallScreen ? 12 : 14,
                                        fontWeight: FontWeight.bold,
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                    )),
                              ),
                            ],
                          )
                        ],
                      ),
                    ),
                  ),
                );
              },
            ),

            const SizedBox(height: 8),
          ],
        ),
      );
    });
  }

  Widget _buildMenuItem({
    required IconData icon,
    required Color iconColor,
    required String title,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(
        icon,
        color: iconColor,
        size: 24,
      ),
      title: Text(
        title,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 16,
        ),
      ),
      onTap: onTap,
      contentPadding: const EdgeInsets.symmetric(horizontal: 20, vertical: 4),
    );
  }

  Widget _buildVersionInfo() {
    return Container(
      padding: const EdgeInsets.all(20),
      child: Obx(() => Text(
            helpController.appVersion.value,
            style: TextStyle(
              color: Colors.grey[600],
              fontSize: 12,
            ),
          )),
    );
  }

  void _showLogoutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color(0xFF2A2A2A),
          title: const Text(
            'Log Out',
            style: TextStyle(color: Colors.white),
          ),
          content: const Text(
            'Are you sure you want to log out?',
            style: TextStyle(color: Colors.white70),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text(
                'Cancel',
                style: TextStyle(color: Colors.grey),
              ),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                authController.logout();
              },
              child: const Text(
                'Log Out',
                style: TextStyle(color: Color(0xFFE6B450)),
              ),
            ),
          ],
        );
      },
    );
  }

  void _showDeleteAccountDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color(0xFF2A2A2A),
          title: const Text(
            'Delete Account',
            style: TextStyle(color: Colors.red),
          ),
          content: const Text(
            'Are you sure you want to delete your account? This action cannot be undone.',
            style: TextStyle(color: Colors.white70),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text(
                'Cancel',
                style: TextStyle(color: Colors.grey),
              ),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
                // TODO: 实现删除账户逻辑
                authController.deleteAccount();
              },
              child: const Text(
                'Delete',
                style: TextStyle(color: Colors.red),
              ),
            ),
          ],
        );
      },
    );
  }

  void _showInvitationCodeDialog() {
    showDialog(
      context: Get.context!,
      builder: (BuildContext context) {
        return InviteCodeDialog();
      },
    );
  }

  void _openWebPage(String url, String title) {
    Get.to(() => WebViewPage(
          url: url,
          title: title,
        ));
  }

  void _showAnnouncementsDialog() {
    showDialog(
      context: Get.context!,
      builder: (BuildContext context) {
        // 获取屏幕尺寸以适应不同屏幕
        final Size screenSize = MediaQuery.of(context).size;
        final double dialogWidth = screenSize.width * 0.85; // 屏幕宽度的85%
        final double dialogHeight = screenSize.height * 0.7; // 屏幕高度的70%

        return Dialog(
          backgroundColor: const Color(0xFF2A2A2A),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          // 设置对话框尺寸，解决"瘦长"问题
          insetPadding: EdgeInsets.symmetric(
            horizontal: screenSize.width * 0.075, // 水平方向留出15%的空间
            vertical: screenSize.height * 0.15, // 垂直方向留出30%的空间
          ),
          child: Container(
            width: dialogWidth,
            constraints: BoxConstraints(
              maxHeight: dialogHeight,
              maxWidth: 500, // 设置最大宽度，避免在大屏幕上过宽
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题栏
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 20, 20, 10),
                  child: Row(
                    children: [
                      Icon(Icons.notifications,
                          color: const Color(0xFFE6B450), size: 24),
                      const SizedBox(width: 12),
                      const Expanded(
                        child: Text(
                          'System Announcements',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      // 添加关闭按钮
                      IconButton(
                        icon: const Icon(Icons.close, color: Colors.white70),
                        onPressed: () => Navigator.of(context).pop(),
                        padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(),
                      ),
                    ],
                  ),
                ),

                const Divider(color: Color(0xFF3A3A3A)),

                // 内容区域
                Flexible(
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.fromLTRB(20, 10, 20, 20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        if (helpController.systemNotice.value.isNotEmpty)
                          Container(
                            padding: const EdgeInsets.all(16),
                            decoration: BoxDecoration(
                              color: const Color(0xFF3A3A3A),
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(
                                  color:
                                      const Color(0xFFE6B450).withOpacity(0.3)),
                            ),
                            // 使用SelectableText.rich替换Text，支持文本选择和链接点击
                            child: SelectableText.rich(
                              _buildClickableTextSpan(
                                  helpController.systemNotice.value),
                              style: const TextStyle(
                                color: Colors.white70,
                                fontSize: 15,
                                height: 1.6,
                              ),
                            ),
                          )
                        else
                          Container(
                            padding: const EdgeInsets.all(20),
                            alignment: Alignment.center,
                            child: const Text(
                              'No announcements at this time.',
                              style: TextStyle(
                                color: Colors.white70,
                                fontSize: 15,
                              ),
                              textAlign: TextAlign.center,
                            ),
                          ),
                      ],
                    ),
                  ),
                ),

                // 底部按钮区域
                Padding(
                  padding: const EdgeInsets.fromLTRB(20, 0, 20, 16),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      ElevatedButton(
                        onPressed: () => Navigator.of(context).pop(),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFFE6B450),
                          foregroundColor: Colors.black,
                          padding: const EdgeInsets.symmetric(
                              horizontal: 24, vertical: 12),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: const Text(
                          'Close',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  // 构建可点击的文本内容（识别邮箱和URL）
  TextSpan _buildClickableTextSpan(String text) {
    // 匹配URL的正则表达式
    final urlRegExp = RegExp(
      r'(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})',
      caseSensitive: false,
    );

    // 匹配邮箱的正则表达式
    final emailRegExp = RegExp(
      r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
      caseSensitive: false,
    );

    // 合并所有匹配项并排序
    final List<Match> matches = [
      ...urlRegExp.allMatches(text),
      ...emailRegExp.allMatches(text),
    ]..sort((a, b) => a.start.compareTo(b.start));

    if (matches.isEmpty) {
      return TextSpan(text: text);
    }

    // 构建文本片段
    final List<TextSpan> spans = [];
    int currentPosition = 0;

    for (final match in matches) {
      // 添加匹配前的普通文本
      if (match.start > currentPosition) {
        spans.add(TextSpan(text: text.substring(currentPosition, match.start)));
      }

      final matchedText = match.group(0)!;

      // 判断是邮箱还是URL
      if (emailRegExp.hasMatch(matchedText)) {
        spans.add(
          TextSpan(
            text: matchedText,
            style: const TextStyle(
              color: Colors.blue,
              decoration: TextDecoration.underline,
            ),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                // 打开邮件应用
                final Uri emailUri = Uri(
                  scheme: 'mailto',
                  path: matchedText,
                );
                launchUrl(emailUri);
              },
          ),
        );
      } else {
        spans.add(
          TextSpan(
            text: matchedText,
            style: const TextStyle(
              color: Colors.blue,
              decoration: TextDecoration.underline,
            ),
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                // 打开网页
                _openWebPage(matchedText, 'Web Page');
              },
          ),
        );
      }

      currentPosition = match.end;
    }

    // 添加最后一段普通文本
    if (currentPosition < text.length) {
      spans.add(TextSpan(text: text.substring(currentPosition)));
    }

    return TextSpan(children: spans);
  }

  void _showPrivacyOptions() {
    ConsentForm.showPrivacyOptionsForm((FormError? formError) {
      if (formError != null) {
        Get.snackbar(
          'Tips',
          'Failed to open privacy options: ${formError.message}',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.red.withOpacity(0.8),
          colorText: Colors.white,
          duration: Duration(seconds: 2),
        );
      } else {
        Get.snackbar(
          'Tips',
          'Privacy options opened. You can update your consent.',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green.withOpacity(0.6),
          colorText: Colors.white,
          duration: Duration(seconds: 2),
        );
      }
    });
  }

  void _showResetConsentDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: const Color(0xFF2A2A2A),
          title: const Text(
            'Reset Privacy Consent',
            style: TextStyle(color: Colors.white),
          ),
          content: const Text(
            'This will revoke your previous privacy consent and re-prompt the consent form. Continue?',
            style: TextStyle(color: Colors.white70),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text(
                'Cancel',
                style: TextStyle(color: Colors.grey),
              ),
            ),
            TextButton(
              onPressed: () async {
                Navigator.of(context).pop();
                final adMobController = Get.find<AdMobController>();
                final ok = await adMobController.resetPrivacyConsent();
                Get.snackbar(
                  ok ? 'Success' : 'Error',
                  ok
                      ? 'Privacy consent reset.'
                      : 'Failed to reset privacy consent.',
                  snackPosition: SnackPosition.BOTTOM,
                  backgroundColor: ok
                      ? Colors.green.withOpacity(0.8)
                      : Colors.red.withOpacity(0.8),
                  colorText: Colors.white,
                  duration: const Duration(seconds: 2),
                );
              },
              child: const Text(
                'Reset',
                style: TextStyle(color: Color(0xFFE6B450)),
              ),
            ),
          ],
        );
      },
    );
  }
}
